package database

import (
	"fmt"
	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
	"github.com/star-find-cloud/star-chat/conf"
	log "github.com/star-find-cloud/star-chat/pkg/logger"
	"sync"
)

type PostgreSQL struct {
	Conn *sqlx.DB
}

var (
	_postgreSQL = &PostgreSQL{}
	_once       sync.Once
)

func init() {
	c := conf.GetConfig()
	user := c.Database.PostgreSQL.User
	passwd := c.Database.PostgreSQL.Password
	host := c.Database.PostgreSQL.Host
	port := c.Database.PostgreSQL.Port
	dbName := c.Database.PostgreSQL.DBName
	sslMode := c.Database.PostgreSQL.SSLMode
	
	// PostgreSQL连接字符串格式
	DSN := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
		host, port, user, passwd, dbName, sslMode)
	
	_once.Do(func() {
		_db, err := sqlx.Connect("postgres", DSN)
		if err != nil {
			fmt.Println("PostgreSQL database error, please check the logs.")
			log.PostgreSQLLogger.Errorf("PostgreSQL connect failed: %s \n", err)
		} else {
			log.PostgreSQLLogger.Infof("PostgreSQL connection successful: %s\n", host)
			_db.SetMaxOpenConns(c.Database.PostgreSQL.MaxOpenConns)
			_db.SetMaxIdleConns(c.Database.PostgreSQL.MaxIdleConns)
			_postgreSQL.Conn = _db
		}
	})
}

func GetPostgreSQL() SQLDatabase {
	return _postgreSQL
}

func (p PostgreSQL) GetDB() *sqlx.DB {
	return p.Conn
}

func (p PostgreSQL) Ping() error {
	return p.Conn.Ping()
}

func (p PostgreSQL) Close() error {
	return p.Conn.Close()
}
